define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/business/record/index',
                    del_url: 'facrm/business/record/del'
                }
            });

            //联系人
            var contact  = $("#table");
            //在普通搜索渲染后
            contact.on('post-common-search.bs.table', function (event, table) {
                $(".commonsearch-table select[name=scene_id]").val(4);
            });
            contact.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar',
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    //params.filter='{"customer_id":'+customer_id+'}';//只是查当前客户的联系人
                    return params
                },
                columns: [
                    [
                        {field: 'id', title: 'ID'},
                        {
                            field: 'scene_id',
                            title: __('记录场景'),
                            visible: false,
                            formatter: function (v,r) {
                                return scene_list[v];
                            },searchList: scene_list},

                        {
                            field: 'types_id',
                            title: __('商机名称'),
                            align: 'left',
                            formatter: function (value, row, index) {
                                if (!row.business)return '-';
                                value='<a href="javascript:void(0);" data-url="facrm/business/index/edit/ids/' + row.types_id
                                    +'" data-area="[&quot;100%&quot;,&quot;100%&quot;]" class="btn-dialog" data-title="'+ row.business.name+'">'+ row.business.name+'('+row.types_id+')'+'</a>';
                                return value;
                            },addclass: 'selectpage',
                            extend: 'data-source="facrm/business/index?filter=%7B\"scene_id\"%3A\"7\"%7D" data-field="name" data-orderBy="id desc"'},

                        {field: 'content', title: __('content'), operate: 'LIKE',    align: 'left',},
                        {field: 'create_user.nickname', title: __('创建人'),operate:false,search:false},
                        {field: 'create_user_id', title: __('创建人'), visible:false,addclass: 'selectpage',
                    			 extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname" data-orderBy="id desc"'},

                        {field: 'create_time', title: __('创建时间'), 
						formatter: Table.api.formatter.datetime, operate: 'RANGE',
						addclass: 'datetimerange', sortable: true,
						extend: 'autocomplete="off"'
						},
                        {field: 'next_time', title: __('下次跟进'), 
						formatter: Table.api.formatter.datetime, operate: 'RANGE', 
						addclass: 'datetimerange', sortable: true,
						extend: 'autocomplete="off"'
						},
                        {field: 'record_type', title: __('跟进类型'),formatter: function (v,r) {
                                return record_type_list[v];
                            },searchList: record_type_list},

                        {field: 'operate', title: __('Operate'), table: contact,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }

                    ]
                ],
                searchFormVisible:true, //打开搜索
            });
            // 初始化表格
            contact.bootstrapTable();
            Table.api.bindevent(contact);//当内容渲染完成后
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name="+field+"]").val(value);
                return false;
            });
        },
        add: function () {
            Controller.api.bindevent();
            $("#buttonshow").click(function () {
                var hiddeninfo= $("#hiddeninfo");
                hiddeninfo.toggle();
                if(hiddeninfo.css('display') === 'none'){
                    $(this).text("显示更多");
                }else{
                    $(this).text("隐藏信息");
                }
            });

            // 初始化表格参数配置

            Table.api.init({
                extend: {
                    index_url: 'facrm/business/record/index/business_id/'+business_id,
                    contact_url:'facrm/business/contacts/index/business_id/'+business_id,
                    product_url:'facrm/business/index/product/business_id/'+business_id,

                }
            });
            var table = $("#tableflow");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
        
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar1',
                columns: [
                    [
                        {field: 'id', title: 'ID'},
                        {field: 'content', title: __('content'), operate: 'LIKE'},
                        {field: 'create_user.nickname', title: __('创建人'),operate:false,search:false},
                        {field: 'create_user_id', title: __('创建人'), visible:false,addclass: 'selectpage',
							extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname" data-orderBy="id desc"'},

                        {field: 'create_time', title: __('创建时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true,
						extend: 'autocomplete="off"'
						},
                        {field: 'next_time', title: __('下次跟进'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true,
						extend: 'autocomplete="off"'},
                        {field: 'record_type', title: __('跟进类型'),formatter: function (v,r) {
                                return record_type_list[v];
                            },searchList: record_type_list},
                        {field: 'files', title: __('附件'),formatter: function (v,row) {
                                if (v.length>0) return '<a href="facrm/business/record/files/types/'+row.types+'/ids/'+row.id+'" class="btn btn-success btn-dialog btn-xs"><i class="fa fa-file-image-o"></i> ' + __('附件') + '</a>';
                            },operate: false},

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            //联系人
            var contact  = $("#contact");
            contact.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.contact_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar2',
                escape: false,
                search: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                showColumns: false,
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    params.filter='{"business_id":'+business_id+'}';//只是查当前客户的联系人
                    return params
                },
                columns: [
                    [
                        {field: 'contact.name', title: __('姓名')},
						
                        {field: 'contact.mobile', title: __('手机'), operate: 'LIKE', formatter: function (value, row, index) {
                                if (!value) return '-';
                                return '<a href="javascript:;" class="btn btn-success cloudcall btn-xs" data-field="mobile" data-typeid="'+
                                    row.contacts_id+'" data-type="customer_contacts" data-name="'+row.contact.name+'"><i class="fa fa-phone"></i> ' +value + '</a>';
                            }},
                        {field: 'contact.telephone', title: __('电话'), operate: 'LIKE', formatter: function (value, row, index) {
                                if (!value) return '-';
                                return '<a href="javascript:;" class="btn btn-success cloudcall btn-xs" data-field="telephone" data-typeid="'+
                                    row.contacts_id+'" data-type="customer_contacts" data-name="'+row.contact.name+'"><i class="fa fa-phone"></i> ' +value + '</a>';
                        }},
                        {field: 'contact.email', title: __('邮箱')},
                        {field: 'contact.wechat', title: __('微信')},
                        {field: 'contact.sex', title: __('性别'),formatter: Table.api.formatter.status, searchList: {0: __('女'), 1: __('男'), '-1': __('未知')}},
                        {field: 'contact.decision', title: __('决策人'),formatter: Table.api.formatter.status, searchList: {0: __('否'), 1: __('是'), '-1': __('未知')}},
                        {field: 'contact.detail_address', title: __('地址')},
                        {field: 'contact.remark', title: __('备注')},
                        {field: 'operate', title: __('Operate'), table: contact,
                            events: Table.api.events.operate,
                            buttons: [
                                {   name: 'del1',
                                    text: '删除',
                                    title: '删除',
                                    confirm:"确认删除？删除关联联系人并不会删除联系人",
                                    icon: 'fa fa-trash',
                                    classname: 'btn btn-xs btn-danger  btn-ajax',
                                    url: 'facrm/business/contacts/del',
                                    success:function(data,ret){
                                        $("a.btn-refresh").trigger("click");
                                    },
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }

                    ]
                ],
            });
            // 初始化表格
            contact.bootstrapTable();
            Table.api.bindevent(contact);//当内容渲染完成后


            //意向产品
            var product_table  = $("#product_table");
            product_table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.product_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbarproduct',
                escape: false,
                search: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                showColumns: false,
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    params.filter='{"business_id":'+business_id+'}';//只是查当前客户的联系人
                    return params
                },
                columns: [
                    [
                        {field: 'info.name', title: __('产品名称')},
                        {field: 'price', title: __('单价')},
                        {field: 'nums', title: __('数量')},
                        {field: 'info.specification', title: __('规格')},
                        {field: 'info.prop', title: __('属性'),formatter: function (v,r) {
                            var str="";
                            if (v!=""){
                                data=$.parseJSON( v );
                                $.each(data, function (i, j) {
                                    str+=str?'<br\>'+j.title+":"+j.value:j.title+":"+j.value;
                                });
                            }
                            return str;
                        }},
                        {field: 'info.sku', title: __('编码')},
                        {field: 'info.unit', title: __('单位')},
                        {field: 'remarks', title: __('备注')},

                    ]
                ],
            });
            // 初始化表格
            product_table.bootstrapTable();
            Table.api.bindevent(product_table);//当内容渲染完成后



            //关联联系人事件
            $(document).on('click', ".correlation", function () {
                parent.Backend.api.open($(this).data("url") , $(this).attr("title"), {callback: correlationCallback});
                return false;
            });
            var correlationCallback = function (data) {
                var contacts_ids="";
                $.each(data, function (i, j) {
                    contacts_ids+=contacts_ids?','+j.id:j.id;
                });

                $.ajax({
                    type:'POST',
                    url:'facrm/business/contacts/correlation',
                    data:{contacts_ids:contacts_ids,business_id:business_id,type:"bind"},
                    dataType:'json',
                    success:function(data){
                        if (data.code==1){
                            Toastr.success(data.msg);
                            $("a.btn-refresh").trigger("click");
                        }else{
                            Toastr.error(data.msg);
                        }
                    },
                    error:function(XMLHttpRequest,textStatus,errorThrown){
                        Toastr.error("请求错误");
                    }
                });



            };

            //发邮件|发信息
            $(".btn-send-email,.btn-send-sms").click(function () {
                var that = this;
                var title = $(that).data('title') || $(that).attr("title") || __('操作');
                var url = $(that).data('url');
                var data = $(that).data() || {};
                delete data.title,data.url;
                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
            });
			//云呼
            $(document).on('click', ".cloudcall", function () {
                var that = this;
                var type = $(that).data('type');
                var typeid = $(that).data('typeid');
                var name = $(that).data('name');
                var field = $(that).data('field');

                Fast.api.ajax({
                    url: 'facrm/setting/cloudcall/call',
                    data: {type: type, typeid: typeid,field:field,name:name}
                }, function (data) {
                    Toastr.success("呼叫成功!");
                    return false;
                });
            });


        },
        edit: function () {

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function (data) {
                    $("#tableflow").bootstrapTable("refresh");
                    $("#record-content").val("");
                    return true;
                });
            }
        }
    };
    return Controller;
});